<?php


namespace App\Common;


use EasySwoole\Component\Singleton;

class RedisSync
{
    use Singleton;

    protected $redisConn;

    //主机
    protected $host = '127.0.0.1';
    /*
     * 端口
     */
    protected $port = '6379';

    public function __construct()
    {
        if (!$this->redisConn) {
            $this->redisConn = new \Redis();
            $this->redisConn->connect($this->host, $this->port);
        }
        return $this->redisConn;
    }

    public function get($key)
    {
        $value = $this->redisConn->get($key);
        $value_serl = json_decode($value, true);
        if ($value_serl) {
            if (is_object($value_serl) || is_array($value_serl)) {
                return $value_serl;
            }
        }
        return $value;
    }

    /**
     * 获取值
     * @param $key
     * @param $value
     * @return bool
     */
    public function set($key, $value, $time = 0)
    {
        if (is_object($value) || is_array($value)) {
            $value = json_encode($value);
        }
        if ($time) {
            $result = $this->redisConn->set($key, $value, $time);
        } else {
            $result = $this->redisConn->set($key, $value);
        }
        return $result;
    }
}
